<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 普通用户不显示账号查询条件 -->
      <el-form-item v-if="!isNormalUser" label="账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开具日期" prop="issuanceDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="主体名称" prop="productionEntity">
        <el-input
          v-model="queryParams.productionEntity"
          placeholder="请输入主体名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 监管者不显示省市区查询条件，普通用户也不显示 -->
      <template v-if="isAdmin">
        <el-form-item label="省" prop="province">
          <el-select v-model="queryParams.province" placeholder="请选择省" clearable @change="handleProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.value"
              :label="province.label"
              :value="province.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="queryParams.city" placeholder="请选择市(请先选择省)" clearable @change="handleCityChange">
            <el-option
              v-for="city in cityOptions"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select v-model="queryParams.district" placeholder="请选择区/县(请先选择市)" clearable>
            <el-option
              v-for="district in districtOptions"
              :key="district.value"
              :label="district.label"
              :value="district.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <!-- 监管者和普通用户显示乡镇/街道查询条件 -->
      <el-form-item v-if="!isAdmin" label="乡镇/街道" prop="township">
        <el-select v-model="queryParams.township" placeholder="请选择乡镇/街道" clearable>
          <el-option
            v-for="township in townshipOptions"
            :key="township.value"
            :label="township.label"
            :value="township.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检验机构" prop="inspectionAgency">
        <el-input
          v-model="queryParams.inspectionAgency"
          placeholder="请输入检验机构"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合格方式" prop="qualificationMethod">
        <el-select v-model="queryParams.qualificationMethod" placeholder="请选择合格方式" clearable>
          <el-option label="自我承诺合格" value="self_commitment" />
          <el-option label="委托检测合格" value="entrusted_detection" />
          <el-option label="内部检测合格" value="internal_detection" />
        </el-select>
      </el-form-item>
      <el-form-item label="合格证编号" prop="certificateNumber">
        <el-input
          v-model="queryParams.certificateNumber"
          placeholder="请输入合格证编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据来源" prop="dataSource">
        <el-select v-model="queryParams.dataSource" placeholder="请选择数据来源" clearable>
          <el-option label="小程序" value="miniprogram" />
          <el-option label="PC端" value="pc" />
          <el-option label="API接口" value="api" />
        </el-select>
      </el-form-item>
      <el-form-item label="被扫查验" prop="scannedVerification">
        <el-select v-model="queryParams.scannedVerification" placeholder="请选择" clearable>
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:certificatePrint:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:certificatePrint:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="certificatePrintList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号" align="center" prop="account" width="130" />
      <el-table-column label="生产主体" align="center" prop="productionEntity" width="200" show-overflow-tooltip />
      <el-table-column label="法人姓名" align="center" prop="legalPersonName" width="120" />
      <el-table-column label="省" align="center" prop="province" width="100" />
      <el-table-column label="市" align="center" prop="city" width="100" />
      <el-table-column label="区/县" align="center" prop="district" width="100" />
      <el-table-column label="镇/乡" align="center" prop="township" width="120" />
      <el-table-column label="详细地址" align="center" prop="detailedAddress" width="200" show-overflow-tooltip />
      <el-table-column label="生产地址" align="center" prop="productionAddress" width="200" show-overflow-tooltip />
      <el-table-column label="食用农产品名称" align="center" prop="productName" width="150" show-overflow-tooltip />
      <el-table-column label="重量(数量)" align="center" prop="weight" width="100" />
      <el-table-column label="单位" align="center" prop="unit" width="80" />
      <el-table-column label="合格方式" align="center" prop="qualificationMethod" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.qualificationMethod == 'self_commitment'" type="primary">自我承诺合格</el-tag>
          <el-tag v-else-if="scope.row.qualificationMethod == 'entrusted_detection'" type="success">委托检测合格</el-tag>
          <el-tag v-else-if="scope.row.qualificationMethod == 'internal_detection'" type="warning">内部检测合格</el-tag>
          <el-tag v-else type="info">{{ scope.row.qualificationMethod }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检验机构" align="center" prop="inspectionAgency" width="150" show-overflow-tooltip />
      <el-table-column label="检测报告" align="center" prop="inspectionReport" width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.inspectionReport"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewReport(scope.row)"
          >查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="开具日期" align="center" prop="issuanceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issuanceDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合格证编号" align="center" prop="certificateNumber" width="150" show-overflow-tooltip />
      <el-table-column label="打印次数" align="center" prop="printCount" width="100" />
      <el-table-column label="扫描次数" align="center" prop="scanCount" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nongjt:certificatePrint:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nongjt:certificatePrint:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleMore(scope.row)"
          >更多</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合格证打印对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产主体" prop="productionEntity">
              <el-input v-model="form.productionEntity" placeholder="请输入生产主体" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人姓名" prop="legalPersonName">
              <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产地址" prop="productionAddress">
              <el-input v-model="form.productionAddress" placeholder="请输入生产地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品重量" prop="weight">
              <el-input-number v-model="form.weight" :precision="2" :step="0.01" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option label="公斤" value="公斤" />
                <el-option label="斤" value="斤" />
                <el-option label="吨" value="吨" />
                <el-option label="个" value="个" />
                <el-option label="箱" value="箱" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格方式" prop="qualificationMethod">
              <el-select v-model="form.qualificationMethod" placeholder="请选择合格方式">
                <el-option label="自我承诺合格" value="self_commitment" />
                <el-option label="委托检测合格" value="entrusted_detection" />
                <el-option label="内部检测合格" value="internal_detection" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开具时间" prop="issuanceDate">
              <el-date-picker clearable
                v-model="form.issuanceDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开具时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格证编号" prop="certificateNumber">
              <el-input v-model="form.certificateNumber" placeholder="请输入合格证编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="打印次数" prop="printCount">
              <el-input-number v-model="form.printCount" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫描次数" prop="scanCount">
              <el-input-number v-model="form.scanCount" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测报告查看对话框 -->
    <el-dialog title="检测报告" :visible.sync="reportOpen" width="80%" append-to-body>
      <div v-if="currentReport">
        <img v-if="isImageFile(currentReport)" :src="currentReport" style="width: 100%; max-height: 600px;" />
        <iframe v-else-if="isPdfFile(currentReport)" :src="currentReport" style="width: 100%; height: 600px;"></iframe>
        <div v-else>
          <p>无法预览此文件类型</p>
          <el-button type="primary" @click="downloadReport">下载文件</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCertificatePrint, getCertificatePrint, delCertificatePrint, addCertificatePrint, updateCertificatePrint } from "@/api/monitor/njt/certificate/print";

export default {
  name: "CertificatePrint",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合格证打印表格数据
      certificatePrintList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示检测报告弹出层
      reportOpen: false,
      // 当前检测报告
      currentReport: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        account: null,
        productionEntity: null,
        productName: null,
        province: null,
        city: null,
        district: null,
        township: null,
        inspectionAgency: null,
        qualificationMethod: null,
        certificateNumber: null,
        dataSource: null,
        scannedVerification: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productionEntity: [
          { required: true, message: "生产主体不能为空", trigger: "blur" }
        ],
        productionAddress: [
          { required: true, message: "生产地址不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        weight: [
          { required: true, message: "产品重量不能为空", trigger: "blur" }
        ]
      },
      // 省市区选项
      provinceOptions: [
        { label: '四川省', value: '四川省' }
      ],
      cityOptions: [],
      districtOptions: [],
      townshipOptions: [],
      // 用户类型判断
      isAdmin: true,
      isNormalUser: false
    };
  },
  created() {
    this.getList();
    this.initRegionData();
    this.checkUserType();
  },
  methods: {
    /** 查询合格证打印列表 */
    getList() {
      this.loading = true;
      listCertificatePrint(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.certificatePrintList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        account: null,
        productionEntity: null,
        legalPersonName: null,
        province: null,
        city: null,
        district: null,
        township: null,
        detailedAddress: null,
        productionAddress: null,
        productName: null,
        weight: null,
        unit: null,
        qualificationMethod: null,
        inspectionAgency: null,
        inspectionReport: null,
        issuanceDate: null,
        certificateNumber: null,
        printCount: null,
        scanCount: null,
        dataSource: null,
        scannedVerification: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合格证打印";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCertificatePrint(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合格证打印";
      });
    },
    /** 查看检测报告 */
    handleViewReport(row) {
      this.currentReport = row.inspectionReport;
      this.reportOpen = true;
    },
    /** 更多按钮操作 */
    handleMore(row) {
      this.$message.info("更多功能开发中...");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCertificatePrint(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificatePrint(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const message = row.id ? '是否确认删除该合格证打印记录？' : '是否确认删除选中的合格证打印记录？';
      this.$modal.confirm(message).then(function() {
        return delCertificatePrint(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/certificatePrint/export', {
        ...this.queryParams
      }, `合格证打印_${new Date().getTime()}.xlsx`)
    },
    // 初始化地区数据
    initRegionData() {
      // 这里应该从后端获取地区数据，暂时使用模拟数据
      this.cityOptions = [
        { label: '成都市', value: '成都市' }
      ];
      this.districtOptions = [
        { label: '郫都区', value: '郫都区' },
        { label: '新都区', value: '新都区' },
        { label: '温江区', value: '温江区' },
        { label: '天府新区', value: '天府新区' }
      ];
      this.townshipOptions = [
        { label: '郫筒街道', value: '郫筒街道' },
        { label: '安德街道', value: '安德街道' },
        { label: '新桥街道', value: '新桥街道' },
        { label: '德源街道', value: '德源街道' },
        { label: '煎茶街道', value: '煎茶街道' }
      ];
    },
    // 检查用户类型
    checkUserType() {
      // 这里应该根据当前登录用户判断用户类型
      // 暂时使用模拟数据
      this.isAdmin = true; // 管理员
      this.isNormalUser = false; // 普通用户
    },
    // 省变化处理
    handleProvinceChange(value) {
      this.queryParams.city = null;
      this.queryParams.district = null;
      this.form.city = null;
      this.form.district = null;
      // 根据省加载市数据
    },
    // 市变化处理
    handleCityChange(value) {
      this.queryParams.district = null;
      this.form.district = null;
      // 根据市加载区县数据
    },
    // 判断是否为图片文件
    isImageFile(url) {
      return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
    },
    // 判断是否为PDF文件
    isPdfFile(url) {
      return /\.pdf$/i.test(url);
    },
    // 下载报告
    downloadReport() {
      if (this.currentReport) {
        window.open(this.currentReport, '_blank');
      }
    }
  }
};
</script>
